﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System.Text;

namespace Apex.IdentityAuth.JWT
{
    /// <summary>
    /// 提供 JWT 身份验证的扩展方法
    /// </summary>
    public static class AuthenticationExtensions
    {
        /// <summary>
        /// 向服务集合中添加 JWT 身份验证
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="jwtOpt">JWT 选项，包括签发者、受众、密钥等信息</param>
        /// <returns>AuthenticationBuilder 实例，用于配置身份验证选项</returns>
        public static AuthenticationBuilder AddJWTAuthentication(this IServiceCollection services, JWTOptions jwtOpt)
        {
            return services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(x =>
                {
                    // 配置 JWT Bearer 身份验证参数
                    x.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = true,                                  // 验证签发者
                        ValidateAudience = true,                                // 验证受众
                        ValidateLifetime = true,                                // 验证过期时间
                        ValidateIssuerSigningKey = true,                        // 验证签名密钥
                        ValidIssuer = jwtOpt.Issuer,                            // 有效的签发者
                        ValidAudience = jwtOpt.Audience,                        // 有效的受众
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtOpt.Key)) // 签名密钥
                    };
                });
        }
    }
}
